"""
自适应模型管理器
根据反馈和性能数据自动选择和优化模型
"""

import time
from typing import Dict, Any, Optional
from src.research_core.model_manager import ModelManager, ModelType
from src.services.feedback_reinforcement_service import get_feedback_driven_rl_service
from src.utils.logging import get_logger

logger = get_logger(__name__)

class AdaptiveModelManager:
    """自适应模型管理器"""
    
    def __init__(self):
        self.model_manager = ModelManager()
        self.feedback_rl_service = get_feedback_driven_rl_service()
        self.model_performance_history: Dict[str, list] = {}
        self.model_selection_stats: Dict[str, Dict[str, int]] = {}
    
    def select_optimal_model(self, task_type: str, context: Dict[str, Any]) -> Optional[Any]:
        """
        根据任务类型和上下文选择最优模型
        
        Args:
            task_type: 任务类型
            context: 上下文信息
            
        Returns:
            Optional[Any]: 最优模型实例
        """
        try:
            # 构建状态
            state = {
                "task_type": task_type,
                "context_complexity": context.get("complexity", "medium"),
                "historical_performance": self._get_historical_performance(task_type)
            }
            
            # 获取推荐动作（模型选择策略）
            action = self.feedback_rl_service.rl_service.get_action(state)
            
            # 根据动作选择模型
            model = self._action_to_model(action, task_type)
            
            # 记录模型选择
            self._record_model_selection(task_type, model.__class__.__name__ if model else "None")
            
            return model
        except Exception as e:
            logger.error(f"选择最优模型失败: {e}")
            # 回退到默认模型
            return self.model_manager.models.get(ModelType.CHAT)
    
    def _get_historical_performance(self, task_type: str) -> float:
        """
        获取历史性能数据
        
        Args:
            task_type: 任务类型
            
        Returns:
            float: 平均性能得分
        """
        history = self.model_performance_history.get(task_type, [])
        if not history:
            return 0.5  # 默认中等性能
        
        # 计算最近10次的平均性能
        recent_history = history[-10:]
        return sum(recent_history) / len(recent_history)
    
    def _action_to_model(self, action: str, task_type: str) -> Optional[Any]:
        """
        将动作映射到具体模型
        
        Args:
            action: 动作
            task_type: 任务类型
            
        Returns:
            Optional[Any]: 模型实例
        """
        # 根据任务类型和动作选择模型
        if task_type == "chat":
            if action == "use_multi_agent_workflow":
                return self.model_manager.models.get(ModelType.CHAT)
            elif action == "use_optimized_workflow":
                return self.model_manager.models.get(ModelType.CHAT)
            else:
                return self.model_manager.models.get(ModelType.CHAT)
        elif task_type == "code_generation":
            return self.model_manager.models.get(ModelType.CODE_GENERATION)
        elif task_type == "image_recognition":
            return self.model_manager.models.get(ModelType.IMAGE_RECOGNITION)
        else:
            return self.model_manager.models.get(ModelType.CHAT)
    
    def _record_model_selection(self, task_type: str, model_name: str):
        """
        记录模型选择统计
        
        Args:
            task_type: 任务类型
            model_name: 模型名称
        """
        if task_type not in self.model_selection_stats:
            self.model_selection_stats[task_type] = {}
        
        self.model_selection_stats[task_type][model_name] = \
            self.model_selection_stats[task_type].get(model_name, 0) + 1
    
    def update_model_performance(self, task_type: str, model_name: str, performance_score: float):
        """
        更新模型性能数据
        
        Args:
            task_type: 任务类型
            model_name: 模型名称
            performance_score: 性能得分
        """
        if task_type not in self.model_performance_history:
            self.model_performance_history[task_type] = []
        
        self.model_performance_history[task_type].append(performance_score)
        
        # 限制历史记录长度
        if len(self.model_performance_history[task_type]) > 100:
            self.model_performance_history[task_type] = self.model_performance_history[task_type][-100:]
    
    def get_adaptation_stats(self) -> Dict[str, Any]:
        """
        获取自适应统计信息
        
        Returns:
            Dict[str, Any]: 统计信息
        """
        return {
            "model_selection_stats": self.model_selection_stats,
            "model_performance_history": {
                task: history[-10:] for task, history in self.model_performance_history.items()
            }
        }


# 创建服务实例
adaptive_model_manager = AdaptiveModelManager()

def get_adaptive_model_manager() -> AdaptiveModelManager:
    """获取自适应模型管理器实例"""
    return adaptive_model_manager